package com.jinyijia.api.infrastructure;

import com.alibaba.fastjson.JSONObject;
import com.jinyijia.api.rest.v1.finance.dto.FinanceDTO;
import com.jinyijia.api.rest.v1.finance.vo.FinanceDetailVO;
import com.jinyijia.api.rest.v1.finance.vo.FinanceVO;
import com.jinyijia.api.rest.v1.order.dto.*;
import com.jinyijia.api.rest.v1.order.vo.FinanceOrderVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author lhw
 * @date 2018/8/13
 **/
@Service
public class FinanceManager {

    @Autowired
    @LoadBalanced
    private RestTemplate restTemplate;

    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public List<FinanceOrderVO> financeOrders(Integer customId) {
        JSONObject orders = restTemplate.getForObject("http://order-service/orders?customInfo.id={1}&status={2}&bill={3}&size=10000", JSONObject.class, customId, OrderStatusDTO.CONFIRM, BillEnumDTO.NOT);
        List<OrderDTO> orderDTOS = orders.getJSONArray("content").toJavaList(OrderDTO.class);
        List<FinanceOrderVO> financeOrderVOS = orderDTOS.stream().map(orderDTO -> new FinanceOrderVO(orderDTO.getCode(), orderDTO.getShopInfo().getName(), orderDTO.getPaymentInfo().size() > 0 ? dateFormat.format(orderDTO.getPaymentInfo().get(0).getPayTime()) : "——", orderDTO.getAmount().doubleValue() / 100, orderDTO.getPaymentInfo().size() > 0 ? orderDTO.getPaymentInfo().get(0).getAmount().doubleValue() / 100 : 0)).collect(Collectors.toList());
        return financeOrderVOS;
    }

    public List<FinanceVO> getHistory(Integer customId) {
        JSONObject histories = restTemplate.getForObject("http://finance-service/finance/invoice?invoiceOrder.customInfo.customId={1}", JSONObject.class, customId);
        List<FinanceDTO> financeDTOS = histories.getJSONArray("content").toJavaList(FinanceDTO.class);
        List<FinanceVO> financeVOS = new ArrayList<>();
        for (FinanceDTO financeDTO : financeDTOS) {
            financeVOS.addAll(financeDTO.getInvoiceOrder().stream().map(invoiceOrder -> new FinanceVO(financeDTO.getInvoiceStatus().getName(), invoiceOrder.getCode(), invoiceOrder.getShopInfo().getName(), Objects.nonNull(invoiceOrder.getPayTime()) ? dateFormat.format(invoiceOrder.getPayTime()) : null, invoiceOrder.getPayAmount().doubleValue() / 100, financeDTO.getAmount().doubleValue() / 100, dateFormat.format(financeDTO.getApplyTime()), financeDTO.getInvoiceType().getName())).collect(Collectors.toList()));
        }
        return financeVOS;
    }

    public Object save(Integer customId, FinanceDTO financeDTO) {
        financeDTO.setAmount((long) (financeDTO.getAmounts() * 100));
        financeDTO.getInvoiceOrder().stream().forEach(invoiceOrder -> {
            JSONObject orders = restTemplate.getForObject("http://order-service/orders?code={1}&customInfo.id={2}", JSONObject.class, invoiceOrder.getCode(), customId);
            OrderDTO orderDTO = orders.getJSONArray("content").toJavaList(OrderDTO.class).get(0);
            invoiceOrder.setCustomInfo(new CustomInfoDTO(orderDTO.getCustomInfo().getId(), orderDTO.getCustomInfo().getUserCode(), orderDTO.getCustomInfo().getName(), orderDTO.getCustomInfo().getId()));
            invoiceOrder.setOrderAmount(orderDTO.getAmount());
            invoiceOrder.setPayAmount(orderDTO.getPaymentInfo().size() > 0 ? orderDTO.getPaymentInfo().get(0).getAmount() : 0);
            invoiceOrder.setPayTime(orderDTO.getPaymentInfo().size() > 0 ? orderDTO.getPaymentInfo().get(0).getPayTime() : null);
            invoiceOrder.setShopInfo(new ShopInfoDTO(orderDTO.getShopInfo().getId(), orderDTO.getShopInfo().getName(), orderDTO.getShopInfo().getImageUrl(), orderDTO.getShopInfo().getId()));
        });
        return restTemplate.postForObject("http://finance-service/finance/invoice", financeDTO, Object.class);
    }

    /**
     * 可开票金额
     */
    public Double credit(Integer customId) {
        try {
            return restTemplate.getForObject("http://order-service/orders/bill/{1}/{2}", Long.class, BillEnumDTO.NOT, customId).doubleValue() / 100;
        } catch (Exception e) {
            return 0D;
        }
    }

    /**
     * 已申请开票金额
     */
    public Double history(Integer customId) {
        try {
            return restTemplate.getForObject("http://finance-service/finance/invoice/history?customId={1}", Long.class, customId).doubleValue() / 100;
        } catch (Exception e) {
            return 0D;
        }
    }

    /**
     * 普票金额
     */
    public Double plain(Integer customId) {
        try {
            return restTemplate.getForObject("http://finance-service/finance/invoice/plain?customId={1}", Long.class, customId).doubleValue() / 100;
        } catch (Exception e) {
            return 0D;
        }
    }

    /**
     * 增票金额
     */
    public Double vat(Integer customId) {
        try {
            return restTemplate.getForObject("http://finance-service/finance/invoice/vat?customId={1}", Long.class, customId).doubleValue() / 100;
        } catch (Exception e) {
            return 0D;
        }
    }

    /**
     * 开票详情
     *
     * @param orderCode
     * @return
     * @author WX
     * @date 2018/8/28
     */
    public FinanceDetailVO get(String orderCode, String applyTime) {
        JSONObject invoice = restTemplate.getForObject("http://finance-service/finance/invoice/order?invoiceOrder.code={1}&applyTime={2}", JSONObject.class, orderCode,applyTime);
        JSONObject invoiceInfo = invoice.getJSONObject("invoiceInfo");
        return new FinanceDetailVO(
                invoiceInfo.getString("shopInfoName"),
                invoiceInfo.getString("applicant"),
                invoiceInfo.getString("mobile"),
                invoiceInfo.getString("bankName"),
                invoiceInfo.getString("bankCard")
        );
    }

}
